package cn.utils;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author 朱颢阳
 * @description
 * @time 2024/8/15 20:35
 */
/*public class saveUtil {
    public static String save(MultipartFile multipartFile){
        //保存到本地
        try {
            String path= null;
            path = ResourceUtils.getURL("classpath:").getPath();
            //输入流
            BufferedInputStream bis=new BufferedInputStream(multipartFile.getInputStream());
            File file=new File(path,"static/images/");
            if(!file.exists()){
                file.mkdirs();
            }
            String fileName=System.currentTimeMillis()+multipartFile.getOriginalFilename();
            String realPath=file.getAbsolutePath()+"/"+fileName;
            //输出流
            BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(realPath));
            byte[] bytes=new byte[1024];
            int d=-1;
            while((d=bis.read(bytes))!=-1){
                bos.write(bytes);
                bos.flush();
            }
            bis.close();
            bos.close();
            String url="http://47.94.122.94:8088/images/"+fileName;
            return url;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}*/


public class saveUtil {
    public static String save(MultipartFile multipartFile) {
        // 保存到本地
        try {
            // 指定保存路径
            String path = "/var/images/";
            File file = new File(path);

            // 确保目录存在，如果不存在则创建
            if (!file.exists() && !file.mkdirs()) {
                throw new IOException("Directory cannot be created: " + path);
            }

            // 生成文件名
            String fileName = System.currentTimeMillis() + "_" + multipartFile.getOriginalFilename();
            String realPath = file.getAbsolutePath() + "/" + fileName;

            // 输入流
            try (BufferedInputStream bis = new BufferedInputStream(multipartFile.getInputStream());
                 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(realPath))) {

                byte[] bytes = new byte[1024];
                int d;
                while ((d = bis.read(bytes)) != -1) {
                    bos.write(bytes, 0, d);  // 写入实际读取的字节数
                }
            }

            // 返回文件的URL
            String url = "https://www.zhuhy0519withjsx.cn/images/" + fileName;
            return url;
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}